package com.ykt.mall.ctrl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.ykt.interceptor.Seach;
import com.ykt.mall.content.Content;
import com.ykt.model.ProductType;
import com.ykt.model.Shop;
import com.ykt.model.ShopType;

@ControllerBind(controllerKey="/shop")//viewPath="/template"

@ClearInterceptor(ClearLayer.UPPER)
public class ShopCtrl  extends Controller {
	private static Logger log = Logger.getLogger(ShopCtrl.class);
	
	@Before(SessionInViewInterceptor.class)
	public void index() {
		Integer shopId= getParaToInt();
		//if(shopId==null) shopId=1;
		Shop shop = Shop.dao.findById(shopId);
		
		setAttr("shopPo", shop);
		
		//System.out.println(shop.getBoolean("has_sub")+"-----Content.SESSION_SHOP------111---------------->"+getSessionAttr(Content.SESSION_SHOP));
		if(getSessionAttr(Content.SESSION_SHOP) == null){
			setSessionAttr(Content.SESSION_SHOP, shop);
		}
		 
		//System.out.println(shop.getBoolean("has_sub")+"-----Content.SESSION_SHOP------222---------------->"+getSessionAttr(Content.SESSION_SHOP));
		
		if(shop.getBoolean("has_sub")!=null && shop.getBoolean("has_sub")){
			
			List<ShopType> shopTypeList = ShopType.dao.find("select * from shop_type where shop_id= ? order by seq ;",shopId);
			Map<Integer,List<Shop>> map = new TreeMap<Integer,List<Shop>>();
			
//			List<Shop> list = new ArrayList<Shop>();
//			String sids = shop.getStr("sids");
//			String[] sidArray = sids.split(",");
//			for(String sid : sidArray){
//				Shop s = Shop.dao.findById(Integer.valueOf(sid));
//				list.add(s);
//			}
			
			for(ShopType stype : shopTypeList){
				int id = stype.getInt("id");
				List<Shop> sList = Shop.dao.find(" select * from shop p where type = ? ",id);
				map.put(id, sList);
			}
			
			setAttr("shopTypeList", shopTypeList);
			setAttr("map",map);
			
//			setAttr("list", list);
//			setAttr("count",list.size());
			
			render("/template/shop/shopList.html");
			return;
		}
		
		//不写返回 默认跳转 /template/shop/view.html
	}
	
	@Before(Seach.class)
	public void shopList(){
		
		Seach seach = getAttr("seachBean");
		int page=getParaToInt("page", 1);
		int rows=this.getParaToInt("rows", 10);
		
//		seach.setSqlWhere(seach.getSqlWhere()+" and name=?");
//		seach.getSqlParam().add("tian");
		
		Page<Shop> data= Shop.dao.paginate(page,rows,null);
		int count = data.getList().size();
		setAttr("page", data);
		setAttr("count",count);
		
	}
}
